package com.titanrise.crm.mapper;

import com.titanrise.crm.domain.dto.MessageDto;
import com.titanrise.crm.domain.model.Messages;
import com.titanrise.crm.environment.annotation.*;

import java.util.List;

import java.time.LocalDateTime;

/**
 * @Description:
 * @Author: pront
 * @Time:2024-11-21 13:51
 */
@Mapper
public interface MessagesMapper {

    @Insert("INSERT INTO tb_messages (message_id, sender_id, receiver_id, content)" +
            "VALUES (#{message.messageId}, #{message.senderId}, #{message.receiverId}, #{message.content})")
    int insertOne(@ParamEntity("message") Messages message);


    @Select("select * from tb_messages where receiver_id = #{receiverId}")
    @ResultType(Messages.class)
    List<Messages> selectAllMsgByReceiverId(@Param("receiver_id") String receiverId);

    @Update("update tb_messages set status = 'READ', read_time = #{readTime} where message_id = #{messageId}")
    int updateStatusById(@Param("messageId") String messageId, LocalDateTime readTime);

    @Delete("delete from tb_messages where message_id = #{messageId}")
    int deleteById(@Param("messageId") String messageId);

    @Delete("delete from tb_messages where receiver_id = #{uid} or sender_id = #{uid}")
    int deleteByReceiverIdOrSenderId(@Param("uid") String uid);

    @Select("SELECT * FROM tb_messages WHERE receiver_id = #{receiverId}")
    List<Messages> selectByReceiverId(@ParamEntity("salespersonId") String receiverId);

    @Select("SELECT tb_messages.*, r_role.name AS sender_name, s_role.name AS receiver_name\n" +
            "FROM tb_messages\n" +
            "         LEFT JOIN tb_role AS r_role ON tb_messages.receiver_id = r_role.uid\n" +
            "         LEFT JOIN tb_role AS s_role ON tb_messages.sender_id = s_role.uid\n" +
            "WHERE tb_messages.receiver_id = #{receiverId};")
    @ResultType(MessageDto.class)
    List<MessageDto> selectDtoByReceiverId(@Param("receiverId") String receiverId);

    @Update("UPDATE tb_messages SET sender_id = #{message.senderId}, receiver_id = #{message.receiverId}, content = #{message.content}, status = #{message.status}, create_time = #{message.createTime}, read_time = #{message.readTime} WHERE message_id = #{message.messageId}")
    int updateMessageById(@ParamEntity("message") Messages message);

}
